package com.ericxu.weixin;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ericxu.weixin.msg.WeiXinMessage;

/**
 * Servlet implementation class WeiXinServlet
 */
@WebServlet("/WeiXinServlet")
public class WeiXinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WeiXinServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		
		if (Authentication.checkAuthentication(signature, timestamp, nonce)) {
			response.getWriter().print(echostr);
		} else {
			response.getWriter().print("Invalid request.");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();

		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		if (!Authentication.checkAuthentication(signature, timestamp, nonce)) {
			out.print("Invalid request.");
			return;
		}
		
		ServletInputStream weixin = request.getInputStream();
		WeiXinMessage msg = WeiXinMessage.createMessage(weixin);
		if (msg != null) {
			out.print(msg.excute().toString());
		} else {
			out.print("");
		}
	}

}
